var express = require('express');
var router = express.Router();
var {
  userModel,
  user,
  stu,
  cate,
  shou,
  lei,
  Order,
  usee,
  d,
  b,
  f,
  h,
  ChatModel,
  ChatsModel,
  DingDanLieBiaoMedol,
  StudenModel,
  CateModel,
  UserModel,

}=require('../model/model')
const crypto = require("crypto"); //引入加密模块
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
//引入阿里云短信服务模块
const SMSClient = require('@alicloud/sms-sdk');
//引入jwt模块
const jwt=require('jsonwebtoken')
let multiparty = require("multiparty");
let AlipaySdk = require("alipay-sdk").default;
let AlipaySdkForm = require("alipay-sdk/lib/form").default;
/* GET home page. */

//加密密码
function md5Password(password){
  const md5=crypto.createHash('md5')
  return md5.update(password).digest('hex')
}
router.post('/adduser',(req,res)=>{
  //加密密码
  userModel.create(req.body)
  res.send({
    code:200,
    msg:'用户添加成功'
  })
})

// 登录
router.post('/login',async(req,res)=>{
  let {username,password}=req.body
  let enycryptedPassword=md5Password(password)
  const users=await user.find({username,password:enycryptedPassword})
  const data=await user.find({username,password:enycryptedPassword})
  //生成token
  let token=jwt.sign({username},'token',{expiresIn:'1d'})
  console.log(users);
  if(users.length>0){
    res.send({
      code:200,
      msg:'登录成功',
      data:data[0],
      token
    })
  }else{
    res.send({
      code:400,
      msg:'用户名或密码错误'
    })
  }
})


//人脸登录
const IaiClient = tencentcloud.iai.v20200303.Client;
router.post('/rllogin', async (req, res) => {
  let { b64 } = req.body
  // console.log(b64);
  if (b64) {
      const clientConfig = {
          credential: {
              secretId: "AKIDIPL3WlodE0awAF7nERPGvLXXPCpRs5BB",//腾讯云账号的secretId
              secretKey: "ykOwTqDRSHtMdiaGm6EQgu4A6rgO0X0J",//腾讯云账号的secretKey
          },
          region: "ap-beijing",
          profile: {
              httpProfile: {
                  endpoint: "iai.tencentcloudapi.com",
              },
          },
      };
      const client = new IaiClient(clientConfig);
      const params = {
          "GroupIds": [
              "100039802084"//   人脸库ID
          ],
          "Image": b64,// 人脸图片的base64编码
          "MaxFaceNum": 1,// 最多返回人脸数
          "MinFaceSize": 80,// 最小人脸大小
          "MaxPersonNum": 5,// 最多返回人脸数
          "NeedPersonInfo": 1,// 0：不需要返回人员库信息；1：需要返回人员库信息
          "QualityControl": 0,// 0：不进行质量检测；1：进行质量检测
          "FaceMatchThreshold": 0// 人脸相似度阈值
      };

      client.SearchFaces(params).then(
          (doc) => {
              let personName = doc.Results[0].Candidates[0].Score > 80 ? doc.Results[0].Candidates[0].PersonName : null

              //生成token
              if (personName !== null) {
                  let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })
                  res.send({
                      code: 200,
                      msg: "登录成功！",
                      token
                  })
              } else {
                  res.send({
                      code: 201,
                      msg: "识别度过低",
                  })
              }
          },
          (err) => {
              res.send({
                  code: 401,
                  msg: '人脸库无此人！'
              })
              console.error("error", err);
              return false
          }
      )
  } else {
      let { username, password } = req.body
      let indexs = await user.find({ phone:username })
      if (indexs.length != 0) {
          let token = jwt.sign({ "name": username }, "face", { expiresIn: '1d' })
          res.send({
              code: 200,
              msg: "登录成功！",
              token
          })
      } else {
          res.send({
              code: 401,
              msg: '用户名或密码错误！'
          })
      }
  }
})


// 产生6位随机数（收到的验证码）
function getCode() {
  let str = "";
  for (let i = 0; i < 6; i++) {
      str += parseInt(Math.random() * 10)
  }
  return str;
}
// 发送短信验证码
router.post('/get_sms', function (req, res, next) {
  let phoneNum = req.body.phone;  //获取前端参数phone
  console.log(phoneNum);
  
  //初始化sms_client
  let smsClient = new SMSClient({
      accessKeyId: 'LTAI5tNyV4AgwZVctwqgA5mS',  //自己阿里云的accessKeyId
      secretAccessKey: 'Gkn7v3b70lxOn5fRykvgwvIX2jjtjH'  //自己阿里云的secretAccessKey
  });

  // 获取6位随机数
  let str = getCode();

  // 开始发送短信
  smsClient.sendSMS({
      PhoneNumbers: phoneNum,
      SignName: "yun2230", //签名名称,阿里云注册
      TemplateCode: "SMS_305050476", //模版CODE,阿里云注册 
      TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
  }).then(r => {
      console.log('执行成功');

      let { Code } = r;
      if (Code == 'OK') {
          res.send({
              code: 200,
              msg: 'success',
              sms: str
          })
          
      }
  })
  .catch(err => {
      res.send({
          code: 400,
          err
      })
  })
});

//注册
router.post('/register',async(req,res)=>{
    let {username,password}=req.body
    console.log(username,password);
    let enycryptedPassword=md5Password(password)
    let data=await user.find({username})
    console.log(data);
    
    if(data.length>0){
      res.send({
        code:400,
        msg:'用户名已存在'
      })
    }else{
      await user.create({username,password:enycryptedPassword})
      res.send({
        code:200,
        msg:'注册成功'
      })
    }
  })
 
//修改密码
router.post('/updatePassword',async(req,res)=>{
    let {username,password}=req.body
    let enycryptedPassword=md5Password(password)
    await user.updateOne({username},{password:enycryptedPassword})
    res.send({
      code:200,
      msg:'修改成功'
    })
})



//赵硕宁
// 支付宝支付
router.post("/alipay", async (req, res) => {
  let { price,name,id } = req.body;
  console.log(id,"53.45645");
  const alipaySdk = new AlipaySdk({   
    appId: '9021000141673604',
    gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
    privateKey: "MIIEpAIBAAKCAQEAq8Gco+koGrZ9HxGnDPK3T2a+DycAVWmMxSf88bvdiEkBoTcn3XG9ps/N6k6u/rKelZGuCOxA47I//ujQanS1qpC1vBSusH9QgmkoSBrCbBFhYF5o9C+VS+tspzIwhChW4RWDPE+0Lyu7jUsfwKhsow1Gzm+AZE/JBuBJCy5eliWNyzTqsu5PttHmQFVdX0WAMUgpaDqfMWKduW8FcbYsUj61cK71SEFrOdApIYiPARf5DcqgTuVRu/SydS2bmbNk67kNbZxchtWQ1CvBgFtVmQAICgfQRUAbOR1F66xtU9vHl2+G5JO+ucFvi9pM2kkdvN/cCqt3kZ1LOsO8Hf70fwIDAQABAoIBAFgYEA2KMwWwf/CFj1b2zsqs+eKvsF4eqxMcdYJPR0r1lx5nOc0833dFsmnxPZRpbSlt9QOimY2wCV7nbq6LefooCu6S9R6Vzmd1JDIHd50SNQ3GnrJQDZVJBQ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tTonuyr8xUjeAf1vU+ZPxsb2HeEMRsQ==",
    alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg99NhY1N4lUWPhP7uSdl4RPCBP8msGOaxJl3jYHdYI2LIDF5191WnoONMY8/02UdbafLz8118tXFBUmy6s7H6PEaYxUDV46OIheXX4kBQpOYAy4N5ZWbzd00ygh3m4aA7PHBL7TMUge5J++8mRvg1830HJg8p7v4Wj9USTMJfY5KeBtcc9/GIOL+G0Yru6DA741zYQsOg4GjuaLjcE8rGP6nNQHdKO7hFORpkGKMgLMv0mKlOj0fyWRcGR0cyb47zUzIi8a93dPg2F5d3rWybI9VxsTdFAm7q2KC9GLzkvlIGScRHC8acGR8V2mEs0ydb5jcw4q10YMxv2GrSHLRewIDAQAB",
    signType: "RSA2",
  });

  const formData = new AlipaySdkForm();
  formData.addField("returnUrl",`http://127.0.0.1:5173/shou/?id=${id}`)
  formData.addField("bizContent", {
    outTradeNo: Date.now(),
    productCode: "FAST_INSTANT_TRADE_PAY",
    totalAmount: price,
    subject: name,
    body: "商品信息",
  });

  //请求第三方接口
  const result = await alipaySdk.exec(
    // "alipay.trade.page.pay",
    "alipay.trade.wap.pay",
    {},
    { formData: formData }
  );
  console.log(result, "result");
  res.send(result);
});



router.post("/stuadd", (req, res) => {
  stu.create(req.body);
  console.log(req.body);
  res.send({
    code: 200,
    msg: "成功",
  });
});
router.post("/cateadd", (req, res) => {
  cate.create(req.body);
  console.log(req.body);
  res.send({
    code: 200,
    msg: "成功",
  });
});

router.post("/leiadd", async (req, res) => {
  let { id, text } = req.body;
  console.log(req.body);
  await cate.updateOne({ _id: id }, { $push: { list: text } });
  res.send({
    code: 200,
    msg: "成功",
  });
});

router.post("/upload", async (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = "upload";
  form.parse(req, (err, a, imgDate) => {
    res.send({
      code: 200,
      path: "http://localhost:3001/" + imgDate.file[0].path,
    });
  });
});

router.get("/stulist", async (req, res) => {
  let { name, num } = req.query;
  let queryArr = [{}];
  let Regname = new RegExp(name);
  if (name) {
    queryArr.push({ name: Regname });
  }
  if (num) {
    queryArr.push({ num: num });
  }

  let stulist = await stu.find({ $and: queryArr });
  let catelist = await cate.find();
  let userlist = await user.find().populate("cate");
  let shoulist = await shou.find()
  let leilist  = await lei.find()
  res.send({
    code: 200,
    stulist,
    catelist,
    userlist,
    shoulist,
    leilist
  });
});

router.get("/aaaa", async (req, res) => {
  let id = req.query.id;
  await cate.updateOne({ _id: id }, { flagg: true });
  res.send({
    code: 200,
    msg: "成功",
  });
});
router.get("/aa", async (req, res) => {
  let id = req.query.id;
  console.log(id);
  let data = await user.find({ _id:  id});
  console.log(data);
  await user.updateOne({ _id: id }, { sum:data[0].sum+1});
  res.send({
    code: 200,
    msg: "成功",
  });
});

router.get("/ssse", async (req, res) => {
  let id = req.query.id;
  console.log(id);
  await cate.updateOne({ _id: id }, { sss: "1" });
  res.send({
    code: 200,
    msg: "成功",
  });
});
router.get("/sssee", async (req, res) => {
  let id = req.query.id;
  console.log(id);
  await cate.updateOne({ _id: id }, { sss: "0" });
  res.send({
    code: 200,
    msg: "成功",
  });
});
router.get("/se", async (req, res) => {
  let id = req.query.id;
  await cate.updateOne({ _id: id }, { sss: 0 });
  res.send({
    code: 200,
    msg: "成功",
  });
});

router.post("/sx", async (req, res) => {
  let sx = req.body;
  console.log(sx);
  let _id = sx._id;

  if (sx.sex == 0) {
    sx.sex = 1;
    await user.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  } else {
    sx.sex = 0;
    await user.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  }
});

router.post("/sxx", async (req, res) => {
  let sx = req.body;
  console.log(sx);
  let _id = sx._id;

  if (sx.numx == 0) {
    sx.numx = 1;
    await stu.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  } else {
    sx.numx = 0;
    await stu.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  }
});

router.post("/sxs", async (req, res) => {
  let sx = req.body;
  console.log(sx);
  let _id = sx._id;

  if (sx.state == 0) {
    sx.state = 1;
    await stu.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  } else {
    sx.state = 0;
    await stu.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  }
});
router.post("/sxss", async (req, res) => {
  let sx = req.body;
  console.log(sx);
  let _id = sx._id;

  if (sx.xxx == 0) {
    sx.xxx = 1;
    await cate.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  } else {
    sx.xxx = 0;
    await cate.updateOne({ _id }, sx);
    res.send({
      code: 200,
      msg: "成功",
    });
  }
});

router.delete("/delall", async (req, res) => {
  let id = req.query.id;

  if (typeof id == "string") {
    await cate.deleteOne({ _id: id });
    res.send({
      code: 200,
      msg: "删除成功",
    });
  } else {
    await stu.deleteMany({ _id: id });
    res.send({
      code: 200,
      msg: "删除成功",
    });
  }
});
router.delete("/delallx", async (req, res) => {
  let id = req.query.id;
  console.log(id);
  if (typeof id == "string") {
    await cate.deleteOne({ _id: id });
    res.send({
      code: 200,
      msg: "删除成功",
    });
  } else {
    await cate.deleteMany({ _id: id });
    res.send({
      code: 200,
      msg: "删除成功",
    });
  }
});

router.post("/edit", async (req, res) => {
  let { id, name } = req.body;
  console.log(id, name);
  await user.updateOne({ _id: id }, { name });
  res.send({
    code: 200,
    msg: "修改成功",
  });
});

router.post("/sss", async (req, res) => {
  let sss = req.body;
  let _id = sss._id;
  console.log(sss._id);
  await stu.updateOne({ _id }, { num: sss.num });
  res.send({
    code: 200,
    msg: "成功",
  });
});


//吴国瑞
router.get("/cate",async(req,res)=>{
  let data = await b.find()
  res.send({
    code:200,
    data
  })
})

router.get("/com",async(req,res)=>{
  let id = req.query.id
  let data = await d.find({pid:id})
  res.send({
    code:200,
    data
  })
})

router.get("/xiang",async(req,res)=>{
  let data = await f.find()
  res.send({
    code:200,
    data
  })
})


router.get("/wen",async(req,res)=>{
  let data = await h.find()
  res.send({
    code:200,
    data
  })
})

router.get("/aa",async(req,res)=>{
  let id = req.query.id
  let data = await h.find({_id:id}).populate("pid")
  res.send({
    code:200,
    data
  })
})

router.post("/add",async(req,res)=>{
  let id = req.body.id
  let text = req.body.text
  await h.updateOne({_id:id},{$push:{ping:{
    img:"https://ts1.cn.mm.bing.net/th/id/R-C.2e4fd5eed869928d4c64f7e86da92889?rik=cbicEOJMb7MGjg&riu=http%3a%2f%2fimg.keaiming.com%2fuploads%2fallimg%2f2020090116%2fi5zb14jg40d.jpg&ehk=6%2bSxzd4A3ko36qil%2bMGWw1q4Q7GPfTQfEYBDuEwC9js%3d&risl=&pid=ImgRaw&r=0",
    name:"洛野",
    context:text
  }}})
  res.send({
    code:200
  })
})

router.get('/chat', async (req, res) => {
  let list = await ChatModel.find()
  res.send({
    list
  })
})

router.post('/chat',(req,res) => {

  ChatModel.create(req.body)

  res.send({code:200})
})


//赵腾鑫
router.get('/list', async (red, res) => {
  let { search } = red.query
  console.log(search);
  
  let data = await CateModel.find({ name: { $regex: search } })
  res.send({
    code: 200,
    data
  })
})
module.exports = router;
